package utils

import (
	"go.uber.org/zap"
	// "bufio"
	"os"
	"path/filepath"
	"strings"
	"unicode/utf8"
)

import (
	"github.com/huichen/sego"
)

type WordFilter struct {
	dirtyWords map[string]bool
	segmenter  sego.Segmenter
	log        *zap.SugaredLogger //获取全局唯一的日志句柄
}

var (
	replaceTo   = "*"
	replaceByte = []byte(strings.Repeat(replaceTo, 1024))
)

func NewWordFilter() *WordFilter {
	return &WordFilter{
		log: Logger(),
	}
}

func (self *WordFilter) InitWordFilter() error {

	// self.dirtyWords = make(map[string]bool)

	// dictPath, dirtyWordsPath := self.dataPath()

	// // 载入字典
	// self.log.Infoln("Loading Dictionary...")
	// // self.segmenter.LoadDictionary(dictPath)
	// self.log.Infoln("Dictionary Loaded")

	// // 读取脏词库
	// self.log.Infoln("Loading Dirty Words...")
	// file, err := os.Open(dirtyWordsPath)
	// if err != nil {
	// 	self.log.Fatalln(err)
	// 	return err
	// }

	// defer file.Close()

	// // 逐行扫描
	// scanner := bufio.NewScanner(file)
	// scanner.Split(bufio.ScanLines)
	// for scanner.Scan() {
	// 	words := strings.Split(strings.ToUpper(strings.TrimSpace(scanner.Text())), " ") // 均处理为大写
	// 	if words[0] != "" {
	// 		self.dirtyWords[words[0]] = true
	// 	}
	// }
	// self.log.Infoln("Dirty Words Loaded")

	return nil
}

func (self *WordFilter) dataPath() (dictPath string, dirtyWordsPath string) {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		return
	}
	curDir := strings.Replace(dir, "\\", "/", -1)

	dirtyWordsPath = curDir + "/wordfilter/dirty.txt"
	_, err = os.Lstat(dirtyWordsPath)
	if err != nil {
		return
	}

	dictPath = curDir + "/wordfilter/dirty.txt," + curDir + "/wordfilter/dictionary.txt"
	return
}

func (self *WordFilter) Filter(input string) (string, error) {
	bin := []byte(input)
	segments := self.segmenter.Segment(bin)
	cleanString := make([]byte, 0, len(bin))
	for _, seg := range segments {
		word := bin[seg.Start():seg.End()]
		if self.dirtyWords[strings.ToUpper(string(word))] {
			cleanString = append(cleanString, replaceByte[:utf8.RuneCount(word)]...)
		} else {
			cleanString = append(cleanString, word...)
		}
	}
	return string(cleanString), nil
}
